/*
 * host_data_mgr.hpp
 *
 *  Created on: 2024年7月8日
 *      Author: Dylan.Gao
 */

#ifndef _DM_OS_SYS_HOST_DATA_MGR_HPP_
#define _DM_OS_SYS_HOST_DATA_MGR_HPP_

#include <boost/interprocess/managed_shared_memory.hpp>
#include <dm/os/types.hpp>

namespace dm{
namespace os{

/**
 * 主机数据管理器
 * 用于管理主机级别的小数据结构
 */
class CHostDataMgr{
	/**
	 * 带互斥的信息
	 * @tparam T
	 */
	template<typename T>
	struct SInfoWithMutex{
		upgradable_mutex_t mutex;
		T info;
	};

	CHostDataMgr();
public:
	static CHostDataMgr& ins();
	static void reset();

	template<typename T>
	T* get(){
		return m_mmgr.find_or_construct<T>(boost::interprocess::unique_instance)();
	}

	template<typename T>
	void free(T* p){
		m_mmgr.destroy_ptr(p);
	}

	template<typename T>
	bool read(SInfoWithMutex<T>* data,T& s,bool(*reader)(const T&,T&)){
		boost::interprocess::sharable_lock<upgradable_mutex_t> sharableLock(data->mutex);
		return reader(data->info,s);
	}

	template<typename T>
	bool write(SInfoWithMutex<T>* data,const T& s,bool(*writer)(const T&,T&)){
		boost::interprocess::scoped_lock<upgradable_mutex_t> scopedLock(data->mutex);
		return writer(s,data->info);
	}

	template<typename T>
	inline bool read(T& s,bool (*reader)(const T&,T&)){
		return read(get<SInfoWithMutex<T> >(),s,reader);
	}

	template<typename T>
	inline bool write(const T& s,bool (*writer)(const T&,T&) ){
		return write(get<SInfoWithMutex<T> >(),s,writer);
	}

private:
	boost::interprocess::managed_shared_memory m_mmgr;
};

}
}

#endif /* _DM_OS_SYS_HOST_DATA_MGR_HPP_ */
